﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

namespace ZooKeeperManage.Helper
{
    public static class Network
    {

        /// <summary>
        /// 用于检查IP地址或域名是否可以使用TCP/IP协议访问(使用Ping命令),true表示Ping成功,false表示Ping失败
        /// </summary>
        /// <param name="ip">输入参数,表示IP地址或域名</param>
        /// <returns></returns>
        public static bool Check(string ip)
        {
            try
            {
                Ping objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions { DontFragment = true };
                string data = "";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = 120;
                PingReply objPinReply = objPingSender.Send(ip, intTimeout, buffer, objPinOptions);
                if (objPinReply != null)
                {
                    string strInfo = objPinReply.Status.ToString();
                    return strInfo == "Success";
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// <summary>
        /// 获取客户端内网IPv4地址
        /// </summary>
        /// <returns>客户端内网IPv4地址</returns>
        /// 
        public static string GetIPv4Address()
        {
            try
            {
                return GetIPv4AddressList()[0];
            }
            catch
            {
                return "unknown";
            }
        }
        /// <summary>
        /// 获取客户端内网IPv4地址集合
        /// </summary>
        /// <returns>返回客户端内网IPv4地址集合</returns>
        public static List<string> GetIPv4AddressList()
        {
            List<string> ipAddressList = new List<string>();
            try
            {
                string hostName = Dns.GetHostName();
                var ipEntry = Dns.GetHostEntry(hostName);
                foreach (IPAddress ip in ipEntry.AddressList)
                // ReSharper disable once RemoveRedundantBraces
                {
                    if (System.Net.Sockets.AddressFamily.InterNetwork.Equals(ip.AddressFamily))
                    {
                        if (!ipAddressList.Contains(ip.ToString())) ipAddressList.Add(ip.ToString());
                    }
                    else if (System.Net.Sockets.AddressFamily.InterNetworkV6.Equals(ip.AddressFamily))
                    {
                    }

                }
            }
            catch
            {
                // ignored
            }

            return ipAddressList;
        }
    }

}
